<?php

namespace Core;

class View {
	
	public $template;
	
	public static $data_global;
	
	public $data;
	
	public $auto = FALSE;
	
	public function __construct($template = 'index')
	{
		$this->template = 'templates/'.$template.'.php';
	}
	
	public static function factory($template)
	{
		return new \Core\View($template);
	}
	
	public function __get($attr)
	{
		echo isset($this->data[$attr]) ? $this->data[$attr] : NULL;
	}
	
	public function __set($attr, $value = NULL)
	{
		$this->data[$attr] = $value;
	}
	
	public function bind_global($index, $value)
	{
		self::$data_blobal[$index] = $value;
	}
	
	public function __toString()
	{
		return $this->render();
	}
	
	public function render()
	{
		if(is_array($this->data))
		{
			foreach($this->data as $index => $obj):
				if(is_object($obj))
				{
					$this->data[$index] = $obj->render();
				}
			endforeach;
		}
		
		if(! empty(self::$data_global))
			extract(self::$data_global);
			
		if(! empty($this->data))
			extract($this->data);
		
		ob_start();
		
		include $this->template;
		$template_content = ob_get_contents();
		
		ob_end_clean();
		
		return $template_content;
	}
	
	public function __destruct()
	{
		if($this->auto)
			echo $this;
	}
	
}